/**
 * create by young (young2f@outlook.com) on 2020/10/30
 */

'use strict';
import {Button, Form, Input, notification, TreeSelect, Transfer, Tree, Select} from 'antd';
import {getMenuData} from '../../../common/menu';
import React, {Component} from 'react';
import moment from 'moment';
import {FormField, FormLayout, ModalFooter} from 'antd-extra';
import ComponentBase from '../../../components/Base/ComponentBase';

const {TreeNode} = Tree;
const units = require('../../../utils/utils');

moment.locale('zh-cn');

@Form.create()
export default class ModalCreateUser extends ComponentBase {
  constructor(props) {
    super(props);
    this.state = {targetKeys: []};
  }

  componentDidMount() {
    const loginInfo = wStore.getStore('loginInfo');
    const {tenantCode} = loginInfo;
    const {role, dispatch} = this.props;
    !role && dispatch({
      type: 'global/getCode',
      payload: {prefix: 'ROL', tenantCode},
    }).then(res => {
      const {code} = res;
      this.setState({code});
    });
  }

  componentWillUnmount() {

  }

  renderFoot = () => {
    const {foot, value, modalRef} = this.props;
    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            const {result} = this.props;
            const {targetKeys} = this.state;
            this.props.form.validateFields((err, values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }
              const loginInfo = wStore.getStore('loginInfo');
              values.createUser = loginInfo.username;
              /**
               * 需要把父节点加进来
               */
              // const {menus} = values;
              targetKeys.map(item => {
                const temp = item.toString().split('/');
                const n = temp.length - 1;
                /**
                 * 子节点
                 * */
                if (n === 2) {
                  const str = `/${temp[1]}`;
                  if (!_.includes(targetKeys, str)) {
                    targetKeys.push(str);
                  }
                }
              });
              console.log('targetKeyss',targetKeys)
              values.menus = targetKeys;
              result(values);
              modalRef.close();
            });
          }}>确定</Button>
          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };
  onChange = targetKeys => {
    this.setState({targetKeys});
  };


  render() {
    const {code} = this.state;
    const {role = {}, form} = this.props;
    const menuData = getMenuData();
    this.editMenuData(menuData);

    const {roleName = '', roleCode = code, menus = [], isAdmin} = role;

    const {targetKeys} = this.state;
    this.state.targetKeys = targetKeys && targetKeys.length ? targetKeys : menus;

    return (
      <div>
        <FormLayout form={form} cols={2}>
          <FormField
            label={'角色编码'}
            name={'roleCode'}
            required={true}
            initialValue={roleCode}
          >
            <Input disabled={true} style={{width: '90%'}}></Input>
          </FormField>
          <FormField
            label={'角色名称'}
            name={'roleName'}
            required={true}
            initialValue={roleName}
          >
            <Input disabled={isAdmin} style={{width: '90%'}}></Input>
          </FormField>

        </FormLayout>
        <TreeTransfer
          listStyle={{
            width: 300,
            height: 640,
          }}
          dataSource={menuData}
          targetKeys={this.state.targetKeys}
          render={item => item.title}
          onChange={this.onChange}/>
        {this.renderFoot()}
      </div>
    );
  }

}

const isChecked = (selectedKeys, eventKey) => {
  return selectedKeys.indexOf(eventKey) !== -1;
};

const generateTree = (treeNodes = [], checkedKeys = []) => {
  return treeNodes.map(({children, ...props}) => (
    <TreeNode {...props} disabled={checkedKeys.includes(props.key)} key={props.key}>
      {generateTree(children, checkedKeys)}
    </TreeNode>
  ));
};
const TreeTransfer = ({dataSource, targetKeys, ...restProps}) => {
  const transferDataSource = [];

  function flatten(list = []) {
    list.forEach(item => {
      transferDataSource.push(item);
      flatten(item.children);
    });
  }

  flatten(dataSource);

  return (
    <Transfer
      {...restProps}
      targetKeys={targetKeys}
      dataSource={transferDataSource}
      // className="tree-transfer"
      render={item => item.title}
      showSelectAll={false}
    >
      {({direction, onItemSelect, selectedKeys}) => {
        if (direction === 'left') {
          const checkedKeys = [...selectedKeys, ...targetKeys];
          return (
            <Tree
              blockNode
              checkable
              checkStrictly
              // defaultExpandAll
              checkedKeys={checkedKeys}
              onCheck={(
                _,
                {
                  node: {
                    props: {eventKey},
                  },
                },
              ) => {
                onItemSelect(eventKey, !isChecked(checkedKeys, eventKey));
              }}
              onSelect={(
                _,
                {
                  node: {
                    props: {eventKey},
                  },
                },
              ) => {
                onItemSelect(eventKey, !isChecked(checkedKeys, eventKey));
              }}
            >
              {generateTree(dataSource, targetKeys)}
            </Tree>
          );
        }
      }}
    </Transfer>
  );
};
